package com.xl.flinkdemo.UDF函数类;

import com.xl.flinkdemo.entity.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import scala.Tuple2;

public class RichFunctionTest {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);
        // 从文件中读取数据
        String inputPath = "D:\\myWork\\flinkdemo\\src\\main\\resources\\sensors";

        //得到数据源
        DataStream<String> inputdataStream = env.readTextFile(inputPath);

        DataStream<SensorReading> dataStream =
                inputdataStream.map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String s) throws Exception {
                        String[] fields = s.split(",");
                        return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
                    }
                });

        DataStream<Tuple2<String,Integer>> resultStream = dataStream.map(new MyMapper());

        resultStream.print();
        env.execute();
    }

    public static class MyMapper extends RichMapFunction<SensorReading, Tuple2<String, Integer>> {

        @Override
        public Tuple2<String, Integer> map(SensorReading sensorReading) throws Exception {
            return new Tuple2<>(sensorReading.getId(),getRuntimeContext().getIndexOfThisSubtask());
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            //初始化工作，一般是定义状态，或者统一和数据库连接一次
            System.out.println("建立算子，open时会被调用，一个分区只调用一次");
        }

        @Override
        public void close() throws Exception {
            System.out.println("关闭连接，做清理操作，一个分区也只调一次");
        }
    }
}
